<template>
  <div ref="pieChart" style="width:100%;height:350px" />
</template>

<script>
import echarts from 'echarts'
import resize from '@/utils/resize'
import { setWatermark } from '@/utils'

export default {
  mixins: [resize],
  props: {
    chartData: {
      type: Array,
      default: () => {}
    },
    title: {
      type: String,
      default: ''
    },
    toolName: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      chart: null,
      data: [],
      legend: []
    }
  },
  watch: {
    chartData(val) {
      this.data = []

      this.data = val
      for (var i = 0; i < this.data.length; i++) {
        this.legend.push(this.data[i].name)
      }

      if (this.chart) {
        this.setOptions()
      } else {
        this.initChart()
      }
    }
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    setOptions() {
      this.chart.setOption({
        backgroundColor: {
          image: setWatermark(),
          repeat: 'repeat'
        },
        title: {
          text: this.title,
          x: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        toolbox: {
          right: 15,
          feature: {
            saveAsImage: {
              backgroundColor: '#FFF'
            },
            dataView: {
              show: true
            }
          }
        },
        legend: {
          bottom: 10,
          data: this.legend
        },
        series: [
          {
            name: this.toolName,
            type: 'pie',
            radius: '55%',
            center: ['50%', '50%'],
            label: {
              show: true,
              formatter: '{b}: {d}%'
            },
            data: this.data,
            itemStyle: {
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              },
              normal: {
                color: (params) => {
                  // 自定义颜色
                  var colorList = ['#C5E1E0', '#CDC3D3', '#E6D2C9', '#E6E7CB', '#B3CBD9', '#bdd6e9', '#bdf3ec', '#d9dcf6', '#ffe7d7', '#d1f5d2', '#cff0ff', '#ffd8d8']
                  return colorList[params.dataIndex]
                }
              }
            }
          }
        ]
      })
    },
    initChart() {
      this.chart = echarts.init(this.$refs.pieChart)
      setTimeout(() => {
        this.setOptions()
      }, 300)
    }
  }
}
</script>
